import axios from 'axios'
import merge from 'lodash/merge'
import qs from 'qs'

let baseUrl = 'http://' + window.location.host
if (process.env.NODE_ENV === 'development') {
  baseUrl = baseUrl + '/api/'
} else {
  baseUrl = 'http://' + window.location.host
}
const defaultConfig = {
  baseURL: baseUrl,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded charset=UTF-8'
  },
  paramsSerializer: function (params) {
    return qs.stringify(params, {arrayFormat: 'indices'}) // indices
  },
  code: 'errCode',
  message: 'errMsg',
  isFileUpload: false
}

export const createInstance = (config) => {
  config = merge({}, defaultConfig, config)
  const instance = axios.create(config)

// request
  instance.interceptors.request.use((config) => {
    const {data} = config
    config.data = config.isFileUpload === true ? data : qs.stringify(data, {arrayFormat: 'indices'})
    return config
  }, (error) => {
    return Promise.reject(error)
  })

// response
  instance.interceptors.response.use((response) => {
    const {config: {responseMapKeys, code}} = response
    let {data} = response

    if (responseMapKeys && data) {
      data = responseMapKeys(data)
    }

    if (data && data[code] !== undefined) {
      return Promise.reject(data)
    }
    return data
  }, (error) => {
    const {config: {code, message}} = error
    if (error[code] !== undefined) {
      return Promise.reject(error)
    }
    if (process.env.NODE_ENV !== 'production') {
      console.error(error)
    }
    return Promise.reject({
      [code]: 500,
      [message]: '服务器繁忙'
    })
  })
  return instance
}
const instance = createInstance()
export default instance

export const base = (params) => {
  return baseUrl
}
